var express = require("express");
const axios = require("axios");
var router = express.Router();

const User = require("../mongoose/models/users");
const { getNextSequenceValue, userFind } = require("./funcs");

/**
 * 用户列表
 */
router.get("/list", function (req, res, next) {
  userFind((data) => {
    res.status(200).send({
      data,
      code: 1,
      msg: "操作成功",
    });
  });
});

router.post("/add", async function (req, res, next) {
  const body = req.body;

  userAddFunc(body, res);
});

const userAddFunc = async (body, res) => {
  body.userid = await getNextSequenceValue("user_id");

  new User(body).save(function (err, users) {
    if (err) {
      res.send({
        code: 999,
        msg: err,
      });
    } else if (!users) {
      res.send({
        code: 999,
        msg: "网络错误",
      });
    } else {
      res.send({
        code: 1,
        data: users,
        msg: "用户注册成功!",
      });
    }
  });
};

router.post("/login", async (req, res, next) => {
  let body = req.body;
  User.findOne({ openid: body.openid }, (err, data) => {
    if (err) {
      // 报错
      res.send({
        code: 999,
        msg: err,
      });
    } else if (!data) {
      // 没有找到
      userAddFunc(body, res);
    } else {
      // 找到
      res.send({
        code: 1,
        data: data,
        msg: "登录成功!",
      });
    }
  });
});

router.post("/del", async function (req, res, next) {
  const { id } = req.body;

  User.deleteOne({ userid: Number(id) }, (err, data) => {
    if (err) {
      res.send({
        code: 999,
        msg: err,
      });
    } else if (!data) {
      res.send({
        code: 999,
        msg: "未查找到相关数据!",
      });
    } else {
      res.send({
        code: 1,
        msg: "删除成功!",
        data,
      });
    }
  });
});

router.get("/userlogin", async function (req, res, next) {
  console.log(req.query, "query");
  const result = await axios.get(
    "https://api.weixin.qq.com/sns/jscode2session",
    {
      params: req.query,
    }
  );
  console.log(result.data, 'resutl');
  res.send(result.data);
});

router.post('/crmLogin', (req, res) => {
  const { account, password } = req.body
  if (account === 'glack' && password === 'zxcvbnm999') {
    res.send({
      code: 1,
      msg: '登录成功!'
    })
  }else{
    res.send({
      code: 500,
      msg: '登录失败!密码错误'
    })
  }
})

module.exports = router;
